package com.watson.spring.all.security.service.old.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.watson.spring.all.security.service.old.entity.Users;
import com.watson.spring.all.security.service.old.mapper.UsersMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author watson
 * @date 2021/5/27 15:20
 * @Description: TODO
 **/
@Service("userDetailsService")
public class MyUserDetailService implements UserDetailsService {
    @Autowired
    private UsersMapper usersMapper;

    /**
     * @param s 用户名
     */
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        //
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", s);
        Users users = usersMapper.selectOne(queryWrapper);
        if (users == null) {
            throw new UsernameNotFoundException("用户名不存在！");
        }

        List<GrantedAuthority> roles = AuthorityUtils
                .commaSeparatedStringToAuthorityList("admins,ROLE_sale");
        //从数据获取，用户的用户名和密码
        return new User(users.getUsername(),
                new BCryptPasswordEncoder().encode(users.getPassword()),
                roles);
    }
}
